const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const pv = require('./middleWare/koa-pv')
const m1 = require('./middleWare/m1')
const m2 = require('./middleWare/m2')
const m3 = require('./middleWare/m3')
const index = require('./routes/index')
const users = require('./routes/users')
const daoke = require('./routes/daoke')
const session = require('koa-generic-session')
const Redis = require('koa-redis')
//dbs
const mongoose = require('mongoose');
const dbConfig = require('./dbs/config');

// error handler
onerror(app)

// middlewares
// app.use(pv())
// app.use(m3())
// app.use(m2())
// app.use(m1())

// 这里传入的两个值作为session加密用
app.keys = ['daoke','daoke2'];
// 如果session没有参数，则默认存入内存中
// redis不传任何参数和则采用安装时的默认值
app.use(session({
  key:'daokeKey', // 这个可以改变存入cookie的session的key
  prefix:'jsonLi', // 这个作为值的前缀可以在redis-cli中通过 “keys *” 查看
  store:new Redis()
}))
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(daoke.routes(), daoke.allowedMethods())

//dbs
mongoose.connect(dbConfig.dbs,{
  useNewUrlParser:true // Mongoose升级到4.x以后要求使用新的url解析器
});

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
